from flask import Blueprint, render_template, jsonify, request,session
from models.entity.remote_host import RemoteHost
import json
from utils.nodetree import get_all_quarter

# 说明： 全部接口已经测试

mod = Blueprint("core_remote_host", __name__, url_prefix="/core/remote_host", template_folder="templates",
                static_folder="static")


@mod.route('/add/', methods=['POST'])
def add_remote_host():
    """新增远程主机"""
    """
    {
    "ip_addr":"192.168.182.121",
    "port":65521,
    "description":"bugaosuni",
    "username":"22dddd",
    "password":"2211lll"
    }
    """
    if request.method == 'POST':
        tmp = {}
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        data = []
        if 'ip_addr' not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = '未定义远程主机'
            tmp['data'] = data
            return jsonify(tmp)
        ip_addr = dict['ip_addr']
        if 'port' not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "未定义远程端口"
            tmp['data'] = data
            return jsonify(tmp)
        port = dict['port']
        description = dict['description']
        if 'username' not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "未定义用户名"
            tmp['data'] = data
            return jsonify(tmp)
        username= dict['username']
        if 'password' not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "未定义密码"
            tmp['data'] = data
            return jsonify(tmp)
        password= dict['password']
        port = dict['port']
        # if RemoteHost.query.filter_by(username=username).filter_by(password=password).filter_by(
        #         ip_addr=ip_addr).filter_by(port=port):
        #     tmp['success'] = 0
        #     tmp['error_code'] = -1
        #     tmp['error_msg'] = "记录已经存在"
        #     tmp['data'] = data
        #     return jsonify(tmp)

        remote_host = RemoteHost()
        remote_host.port =port
        remote_host.ip_addr = ip_addr
        remote_host.port = port
        remote_host.username = username
        remote_host.password = password
        remote_host.description = description

        if remote_host.save():
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -3
            tmp['error_msg'] = "未知错误"
            tmp['data'] = data
            return jsonify(tmp)




@mod.route('/del/', methods=['POST'])
def del_quarter():
    """删除远程主机"""
    """
    {
    "id": 2
    }
    """
    if request.method == 'POST':
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        id = dict['id']
        data = []
        tmp = {}
        remote_host = RemoteHost.get_remote_host_by_id(id)
        if not remote_host:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "记录不存在，请重新选择"
            tmp['data'] = data
            return jsonify(tmp)

        if remote_host.delete():
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "未知错误"
            tmp['data'] = data
            return jsonify(tmp)


# 此方法弃用
# @mod.route('/get_all_tree/', methods=['GET', 'POST'])
# def get_all_quarter_tree():
#     """得到全部子区域"""
#     receive = request.data
#     dict = json.loads(receive.decode("utf-8"))
#     id = dict['id']
#     quarters_root = Quarter.query.filter_by(department_id=id).all()
#     data = []
#     tmp = {}
#     all_tree_node = []
#     for item in quarters_root:
#         t_list = []
#         for t in Quarter.query.filter_by(department_id=id).all():
#             if t.path.split(',')[0] == str(item.id):
#                 t_list.append(t)
#         all_tree_node.append(t_list)
#     rlist = []
#     count = 0
#     while count < len(quarters_root):
#         tmps = get_all_quarter(all_tree_node[count], 0)
#         if tmps==[]:
#             pass
#         else:
#             rlist.append(get_all_quarter(all_tree_node[count], 0)[0])
#         count += 1
#     tmp['data'] = rlist
#     tmp['success'] = 1
#     tmp['error_code'] = None
#     tmp['error_msg'] = None
#     tmp['data'] = rlist
#     return jsonify(tmp)


"""
@mod.route('/edit', methods=['GET', 'POST'])
def edit_district_master():
    得到字典列表中的字典项"""



@mod.route('/edit/', methods=[ 'POST'])
def edit():
    """编辑远程主机"""
    if request.method == 'POST':
        tmp = {}
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        data = []
        if 'id' not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "请选择对应的记录"
            tmp['data'] = data
            return jsonify(tmp)
        id = dict['id']
        remote_host = RemoteHost.get_remote_host_by_id(id)
        ip_addr = dict['ip_addr']
        port = dict['port']
        username = dict['username']
        password = dict['password']
        description = dict['description']
        # if port != remote_host.port or username != remote_host.username or ip_addr != remote_host.ip_addr or password != remote_host.password:
        #     if RemoteHost.query.filter_by(username=username).filter_by(password=password).filter_by(
        #             ip_addr=ip_addr).filter_by(port=port):
        #         tmp['success'] = 0
        #         tmp['error_code'] = -1
        #         tmp['error_msg'] = "记录已经存在"
        #         tmp['data'] = data
        #         return jsonify(tmp)
        remote_host.ip_addr =ip_addr
        remote_host.password = password
        remote_host.port =port
        remote_host.username = username
        remote_host.description =description
        if remote_host.save():
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "未知错误"
            tmp['data'] = data
            return jsonify(tmp)

# @mod.route('/edit/', methods=['POST'])
# def edit_remote_host():
#     """编辑远程主机"""
#     if request.method == 'POST':
#         tmp = {}
#         receive = request.data
#         dict = json.loads(receive.decode("utf-8"))
#         data = []
#         if 'id' not in dict:
#             tmp['success'] = 0
#             tmp['error_code'] = -1
#             tmp['error_msg'] = "请选择对应的"
#             tmp['data'] = data
#             return jsonify(tmp)
#         id = dict['id']
#         remote_host = RemoteHost.get_remote_host_by_id(id)
#         ip_addr = dict['ip_addr']
#         port = dict['port']
#         username = dict['username']
#         password = dict['password']
#         description = dict['description']
#         remote_host.ip_addr =ip_addr
#         remote_host.password = password
#         remote_host.port =port
#         remote_host.username = username
#         remote_host.description =description
#         if remote_host.save():
#             tmp['success'] = 1
#             tmp['error_code'] = None
#             tmp['error_msg'] = None
#             tmp['data'] = data
#             return jsonify(tmp)
#         else:
#             tmp['success'] = 0
#             tmp['error_code'] = -1
#             tmp['error_msg'] = "未知错误"
#             tmp['data'] = data
#             return jsonify(tmp)

@mod.route('/get_all/', methods=['POST'])
def get_remote_host_all():
    """得到远程主机"""
    if request.method == 'POST':
        tmp ={}
        data = []
        remote_hosts = RemoteHost.get_remote_host_all()
        for item in remote_hosts:
            data.append(item.get_dic())
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return jsonify(tmp)




@mod.route("/search/",methods=["POST"])
def quarter_search():
    """
    模糊搜索接口
    """
    # request: json
    # {
    #       "query_word":"query_word"
    # }
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        error_msg={
                                        "success":0,
                                        "error_code":-1,
                                        "error_msg":"json格式错误"
                            }
        return jsonify(error_msg)
    if "query_word" in data:
        query_word=data["query_word"]
    else:
        error_msg={
                                        "success":0,
                                        "error_code":-2,
                                        "error_msg":"数据不完整"
                            }
        return jsonify(error_msg)
    rdic=RemoteHost.search(query_word)
    return jsonify(rdic)